package com.slipper.websocket;

import com.slipper.common.bo.UserDetail;
import com.slipper.constants.Constants;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.lang.NonNull;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

public class WebsocketInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(
            @NonNull ServerHttpRequest request,
            @NonNull ServerHttpResponse response,
            @NonNull WebSocketHandler wsHandler,
            @NonNull Map<String, Object> attributes) {
        HttpSession session = ((ServletServerHttpRequest) request).getServletRequest().getSession();
        UserDetail user = Constants.getSessionUser(session);
        if (user == null) return false;

        attributes.put("userId", user.getEmployeeId());
        attributes.put("userName", user.getEmployee().getName());
        return true;
    }

    @Override
    public void afterHandshake(
            @NonNull ServerHttpRequest request,
            @NonNull ServerHttpResponse response,
            @NonNull WebSocketHandler wsHandler,
            Exception exception) {
    }

}
